﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IServices.SalesOrder;
using ProTrack.IServices.StoreHouse;
using ProTrack.Report;
using ProTrack.Utility;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Printing;
using System.Linq;
using System.Threading.Tasks;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 客户报价单接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class OrderQuoteController : ControllerBase
    {
        public OrderQuoteController(IOrderQuoteServices services,LogHelper LogHelper)
        {
            Services = services;
            this.LogHelper = LogHelper;
        }

        public IOrderQuoteServices Services { get; }
        public LogHelper LogHelper { get; }


        /// <summary>
        /// 获取所有客户报价单数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();

            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";


                //写日志
                await LogHelper.WriteErrorLog("客户报价单-获取所有", ex, HttpContext);
            }
            return Ok(status);
        }


        /// <summary>
        /// 分页获取客户报价单数据
        /// </summary>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">页大小</param>
        /// <param name="Number">报价单编号</param>
        /// <param name="CustomerName">客户编号</param>
        /// <param name="EmployeesId">报价人</param>
        /// <param name="WarehouseId"></param>
        /// <param name="Status">出货仓</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string Number, [FromQuery] string CustomerNumber, [FromQuery] string EmployeesId, [FromQuery] string WarehouseId, [FromQuery] string Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                Number = Number ?? "";
                CustomerNumber = CustomerNumber ?? "";
                EmployeesId = EmployeesId ?? "";
                WarehouseId = WarehouseId ?? "";
                Status = Status ?? "";

                var list = await Services.GetAsync(PageIndex, PageSize, Number, CustomerNumber, EmployeesId, WarehouseId, Status);
                status.Data = list;
                status.Count = await Services.GetCountAsync( Number, CustomerNumber, EmployeesId, WarehouseId, Status);

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";

                //写日志
                await LogHelper.WriteErrorLog("客户报价单-分页获取", ex, HttpContext);
            }
            return Ok(status);
        }


        /// <summary>
        /// 根据报价单Id获取商品数据
        /// </summary>
        /// <param name="OrderQuoteId">单据Id</param>
        /// <param name="WareHouseId">仓库Id</param>
        /// <returns></returns>
        [HttpGet("GetOrderQuotebyId")]
        public async Task<IActionResult> GetOrderQuotebyId([FromQuery] string OrderQuoteId, [FromQuery]  string WareHouseId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {

                var list = await Services.GetOrderQuotebyIdAsync(OrderQuoteId, WareHouseId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("工作站-获取设备资源", ex, HttpContext);
            }
             
            return Ok(status);
        }

        /// <summary>
        /// 新增客户报价单
        /// </summary>
        /// <param name="model">规格模型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] OrderQuote model,[FromForm] string OrderQuoteItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<OrderQuoteItem> list = new List<OrderQuoteItem>();
            try
            {
                if (!string.IsNullOrEmpty(OrderQuoteItemString))
                {
                    list = JsonConvert.DeserializeObject<List<OrderQuoteItem>>(OrderQuoteItemString);
                    list.ForEach(x => {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                        //主表Id由于是自增，由内部方法自动赋值,无需手动介入
                    });
                }
                model.CreateTime = StringHelper.GetTimeNow();
                model.Creator = User.Identity.Name;

                var isSuccess = await Services.AddAsync(model,list);
                if (isSuccess)
                {
                    status.Msg = "新增成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("报价单-新增", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 修改规格
        /// </summary>
        /// <param name="model">规格模型</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] OrderQuote model, [FromForm] string OrderQuoteItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<OrderQuoteItem> list = new List<OrderQuoteItem>();
            try
            {
                if (!string.IsNullOrEmpty(OrderQuoteItemString))
                {
                    list = JsonConvert.DeserializeObject<List<OrderQuoteItem>>(OrderQuoteItemString);
                    list.ForEach(x => {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                        //主表Id由于是自增，由内部方法自动赋值,无需手动介入


                        x.OrderQuoteId = model.Id;
                    });
                }
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = User.Identity.Name;
                var isSuccess = await Services.UpdateAsync(model, list);
                if (isSuccess)
                {
                    status.Msg = "修改成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("报价单-修改", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 批量删除报价单数据
        /// </summary>
        /// <param name="Ids">Id数组</param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteAsync(arr);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("报价单-批量删除", ex, HttpContext);
            }

            return Ok(status);
        }




        /// <summary>
        /// 修改报价单状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        [HttpPut("updateQuoteStatus")]
        public async Task<IActionResult> updateQuoteStatus([FromForm] int Id, [FromForm]string Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                // 根据报价单 Id 查询数据库，找到对应的报价单对象
                var quote = await Services.updateQuoteStatus(Id, Status);


                if (quote == null)
                {
                    // 如果未找到对应的报价单，返回错误状态信息
                    status.Code = -1;
                    status.Msg = "未找到该报价单";
                }
                else
                {
                    // 更新报价单状态
                    //quote.Status = Status;

                    status.Code = 0;
                    status.Msg = "报价单状态更新成功";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("报价单-修改状态", ex, HttpContext);
            }

            return Ok(status);
        }



        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet("Export")]
        public async Task<IActionResult> Export()
        {
            try
            {

                var list = await Services.GetAllAsync();
                var TitleArray = new ReportDomain[] {
                    new ReportDomain{ Title="序号",Fileld="No"},
                    new ReportDomain{ Title="报价单编号",Fileld="Number"},
                    new ReportDomain{ Title="客户名称",Fileld="CustomerName"},
                    new ReportDomain{ Title="出货仓",Fileld="WarehouseName"},
                    new ReportDomain{ Title="运输方式",Fileld="Transfer"},
                    new ReportDomain{ Title="运输方式",Fileld="Transfer"},
                    new ReportDomain{ Title="报价人",Fileld="EmployeesName"},
                    new ReportDomain{ Title="报价单状态",Fileld="Status"},
                    new ReportDomain{ Title="出库日期",Fileld="CreateTime"},
                    new ReportDomain{ Title="备注",Fileld="Remark"},

                };
                var fileArray = BaseReport.Export(list, "报价单信息", TitleArray);

                return File(new System.IO.MemoryStream(fileArray), "application/octet-stream", "报价单信息.xls");
            }
            catch (Exception ex)
            {

                //此处应当日志记录
                await LogHelper.WriteErrorLog("报价单信息-导出", ex, HttpContext);
                return new JsonResult(BaseStatus.CreateInstance(-1, "导出失败，服务器异常请稍后再试！"));
            }

        }


    }
}
